# -*- coding: utf-8 -*-
# Project : flacon
# File : settings.py
# (c) Alexander Sokolov sokoloff.a@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.


from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import *
import subprocess


#****************************************************************
#
#****************************************************************
class PregapFileTypes:
    ExtractToFile   = 'extract'
    AddToFirstTrack = 'addToFirst'



#****************************************************************
#
#****************************************************************
class Settings(QSettings):
   #****************************************************************
   #
   #****************************************************************
    def __init__(self, organization, application):
        QSettings.__init__(self, organization, application)

        self._programs = []

        defaults = {
            'Tags/DefaultCodepage':        'AUTODETECT',

            # Globals *************************************************
            'Encoder/ThreadCount':  8,
            'Encoder/TmpDir':       '',
            'PerTrackCue/Create':   False,
            'PerTrackCue/Pregap':   PregapFileTypes.ExtractToFile,

            # Out Files ***********************************************
            'OutFiles/Pattern':     '%a/%y - %A/%n - %t',
            'OutFiles/Directory':   '~/music',
            'OutFiles/Format':      'FLAC',

            # Internet *************************************************
            'Inet/CDDBHost':        'freedb.freedb.org',
        }

        self._defaults = {}
        for key, val in defaults.iteritems():
            self._defaults[QString(key)] = QVariant(val)

        self.addPrograms(['shntool'])


   #****************************************************************
   #
   #****************************************************************
    def programs(self):
        return self._programs


   #****************************************************************
   #
   #****************************************************************
    def addPrograms(self, programs):
        for program in programs:
            program = str(program)
            if program in self._programs:
                return

            self._programs.append(program)
            if (self.value('Programs/'+program).toString().isEmpty()):
                self.setValue('Programs/'+program, self.findProgram(program))


   #****************************************************************
   #
   #****************************************************************
    def value(self, key, defaultValue = None):
        key = QString(key)
        if defaultValue == None:
            try:
                defaultValue = self._defaults[key]
            except KeyError:
                defaultValue = QVariant()

        return QSettings.value(self, key, QVariant(defaultValue))


   #****************************************************************
   #
   #****************************************************************
    def defaultValue(self, key):
        key = QString(key)

        try:
            return self._defaults[key]
        except KeyError:
            return QVariant()


   #****************************************************************
   # Sets the value of setting key to value.
   #****************************************************************
    def setValue(self, key, value):
        QSettings.setValue(self, QString(key), QVariant(value))
        self.emit(SIGNAL("changed()"))


   #****************************************************************
   #
   #****************************************************************
    def findProgram(self, program):
        path = subprocess.Popen(["which", program], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
        return QString(path).trimmed()


   #****************************************************************
   #
   #****************************************************************
    def checkProgram(self, programKey):
        val = self.value(programKey).toString()
        if val.isEmpty():
            return False

        return QFileInfo(val).exists()


   #****************************************************************
   #
   #****************************************************************
    def event(self, event):
        res = QSettings.event(self, event)
        if event.type() == QEvent.UpdateRequest:
            self.emit(SIGNAL("Changed()"))

        return res


   #****************************************************************
   #
   #****************************************************************
    def addDefaults(self, defaults):
        for (key, val) in defaults.items():
            self._defaults[QString(key)] = QVariant(val)



settings = Settings('flacon', 'flacon')
